package org.witsoft.dtx.example.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.witsoft.dtx.LocalTransactionManager;
import org.witsoft.dtx.example.domain.WalletEvent;
import org.witsoft.dtx.example.service.TransferService;
import org.witsoft.dtx.example.service.WalletService;

import java.math.BigDecimal;

/**
 * @author XiaoQing Lin
 * @date 2020-09-21 16:04
 */
@Service
public class TransferServiceImpl implements TransferService {

    @Autowired
    private WalletService walletService;

    @Autowired
    private LocalTransactionManager transactionManager;

    public void transfer(int fromUserId, int toUserId, BigDecimal money) {
        String orderId = "zz-" + (System.currentTimeMillis() - 1577808000000L);
        transactionManager.begin();
        try{
            transactionManager.beginBranch("out", WalletTransferOutHandler.class, fromUserId + "|" + orderId);
            boolean flag = walletService.decrease(fromUserId, money, WalletEvent.TRANSFER_OUT, orderId , false, "转账");
            if(flag){
                transactionManager.beginBranch("in", WalletTransferInHandler.class, toUserId + "|" + orderId);
                walletService.increase(toUserId, money, WalletEvent.TRANSFER_IN, orderId, true, "转账");
            }
            if(1 == 1){
//                throw new RuntimeException("模拟异常");
            }
            transactionManager.commit(false);
        }finally {
            transactionManager.release(false);
        }
    }
}
